<template>
  <div class="agent-apply__wrapper">
    <div class="logo-img">
      <img :src="require('../../assets/images/login-logo.png')" alt="" />
      <img :src="require('../../assets/images/chinamobile.png')" alt="" />
    </div>
    <div class="agent-apply__body">
      <p class="title">账号申请</p>
      <div>
        <i-form
          ref="agentApplyForm"
          :class="{
            'hidden-form': step === 2,
            'add-form': true,
          }"
          label-position="left"
          :label-width="labelWidth"
          :model="agentApplyFormData"
          :items="agentApplyFormItems"
          :rules="agentApplyFormRules"
        >
          <template slot="imgCode">
            <el-form-item label="图形验证码" prop="imgCode">
              <div class="autcode-content mobile-dialog-autcode_content">
                <el-input
                  v-model="agentApplyFormData.imgCode"
                  class="authCode"
                  :maxlength="4"
                />
                <div
                  class="login-right_code mobile-dialog-autcode_content_right"
                >
                  <img class="code" :src="authCodeSrc" />
                  <span class="create-code" @click="createCode">换一张</span>
                </div>
              </div>
            </el-form-item>
          </template>
          <template slot="code">
            <el-form-item label="验证码" prop="code">
              <div class="autcode-content mobile-dialog-autcode_content">
                <el-input class="authCode" v-model="agentApplyFormData.code" />
                <div class="mobile-dialog-autcode_button">
                  <HycTimerButton
                    :user-mobile="agentApplyFormData.mobile"
                    :user-validation-code="agentApplyFormData.imgCode"
                    :key="buttonkey"
                    @changeValidationCode="createCode"
                  />
                </div>
              </div>
            </el-form-item>
          </template>
        </i-form>
        <i-form
          ref="submitForm"
          :class="{
            'hidden-form': step === 1,
            'add-form': true,
          }"
          label-position="left"
          :label-width="labelWidth"
          :model="submitForm"
          :items="submitFormItems"
          :rules="submitFormRules"
          :key="step"
        >
          <template slot="address">
            <el-form-item label="选择地区" prop="area" required>
              <HycAddressCascader ref="area" v-model="submitForm.area" />
            </el-form-item>
          </template>
          <template slot="cooperationUrl">
            <el-form-item label="合作协议" prop="cooperationUrl">
              <hyc-form-upload
                ref="bl_pic"
                v-model="submitForm.cooperationUrl"
                :upload-data="stationImgData"
              >
              </hyc-form-upload>
            </el-form-item>
          </template>
          <template slot="licenseUrl">
            <el-form-item label="营业执照" prop="licenseUrl">
              <hyc-form-upload
                ref="bl_pic"
                v-model="submitForm.licenseUrl"
                :upload-data="stationImgData"
              >
              </hyc-form-upload>
            </el-form-item>
          </template>
        </i-form>
        <div v-if="step === 2" class="agent-apply-agreement">
          <el-checkbox v-model="agree" />
          我已阅读并同意
          <a :href="agreementUrl" target="_blank">《商户协议》</a>
        </div>
        <div class="agent-apply-buttons">
          <el-button v-if="step === 1" type="primary" @click="nextStep"
            >下一步</el-button
          >
          <el-button
            v-if="step === 2"
            type="primary"
            @click="handleApply"
            :disabled="!agree"
          >
            立即申请
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import md5 from 'md5'
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min.js'
import hycFormUpload from '@/components/hycFormUpload'
import HycAddressCascader from '@/components/hycAddressCascader'
import HycTimerButton from '@/components/hycTimerButton'
import formValidate from '@/utils/validate'
import { appConfig } from '@/config'
// import { agentConfig } from '@/config/angentConfig'
import { openMerchantCode, merchantApply, getWebLoginImg } from '@/api/common'
import { getUser } from '@/utils/storage'
import { cloneDeep } from 'lodash'

const merchantType = {
  // ANOTHER: '其他运营方',
  CMCC: '中国移动',
  CTT: '中国铁通',
}

export default {
  name: 'AgentApply',
  components: {
    hycFormUpload,
    HycAddressCascader,
    HycTimerButton,
  },
  watch: {
    'submitForm.merchantType': {
      handler(val, oldval) {
        if (val === oldval) return

        console.log('changeItems')
        let index = this.submitFormItems.findIndex(
          (item) => item.value === 'merchantLevel'
        )
        if (index < 0) return
        if (val === 'CMCC') {
          this.$set(this.submitFormItems, index, {
            ...this.submitFormItems[index],
            options: [
              {
                label: '省移动',
                value: 'PROVINCE',
              },
              {
                label: '市移动',
                value: 'CITY',
              },
              {
                label: '区（县）移动',
                value: 'DISTRICT',
              },
            ],
          })
        } else {
          this.$set(this.submitFormItems, index, {
            ...this.submitFormItems[index],
            options: [
              {
                label: '省铁通',
                value: 'PROVINCE',
              },
              {
                label: '市铁通',
                value: 'CITY',
              },
              {
                label: '区（县）铁通',
                value: 'DISTRICT',
              },
            ],
          })
        }
      },
      immediate: true,
    },
    'submitForm.merchantLevel': {
      handler(val, oldval) {
        if (val === oldval) return
        if (this.submitForm.area)
          this.$refs.submitForm.$refs.form.validateField('area')
      },
      immediate: true,
    },
    'submitForm.password': {
      handler(val, oldVal) {
        if (val === oldVal) return

        if (val === this.submitForm.newpassword) {
          this.$refs.submitForm.$refs.form.clearValidate('newpassword')
        } else {
          if (
            this.submitForm.newpassword &&
            this.submitForm.newpassword !== ''
          ) {
            this.$refs.submitForm.$refs.form.validateField('newpassword')
          }
        }
      },
    },
  },
  computed: {
    applyButtonType() {
      return this.agree ? 'primary' : 'info'
    },
  },
  data() {
    return {
      agreementUrl:
        process.env.VUE_APP_DOMAIN_NAME + '/appPage/merchantAgreement.html',
      agree: false,
      merchantCode: null,
      stationImgData: { fileType: 'IMAGE' },
      buttonkey: 1,
      authCodeSrc: '',
      loginUser: getUser(),
      imageUrl: appConfig.imageValidationUrl,
      agentApplyFormData: {
        merchantType: 'ANOTHER',
      },
      submitForm: {
        merchantType: 'CMCC',
      },
      submitFormItems: [
        {
          type: 'radio',
          value: 'merchantType',
          label: '商户单位',
          required: true,
          options: () => {
            return Object.keys(merchantType).map((item) => {
              return {
                label: item,
                text: merchantType[item],
              }
            })
          },
          ifRender: () => {
            return this.agentApplyFormData.merchantType !== 'ANOTHER'
          },
        },
        {
          type: 'select',
          value: 'merchantLevel',
          label: '商户级别',
          placeholder: '-- 请选择 --',
          required: true,
          clearable: true,
          options: [],
          ifRender: () => {
            return this.agentApplyFormData.merchantType !== 'ANOTHER'
          },
        },
        {
          slot: 'address',
        },
        {
          type: 'text',
          value: 'serviceMobile',
          label: '客服电话',
          placeholder: '请输入客服电话（手机号或固定电话）',
          required: true,
          clearable: true,
        },
        {
          type: 'password',
          value: 'password',
          label: '设置密码',
          'show-password': true,
          clearable: true,
          autoComplete: 'new-password',
          placeholder: '须包含数字、字母及特殊字符，长度不小于8位',
        },
        {
          type: 'password',
          value: 'newpassword',
          label: '确认密码',
          placeholder: '确认密码',
          autoComplete: 'off',
          'show-password': true,
          clearable: true,
        },
        {
          slot: 'cooperationUrl',
        },
        {
          slot: 'licenseUrl',
        },
        {
          type: 'text',
          value: 'remark',
          label: '备注',
          placeholder: '非必填',
        },
      ],
      submitFormRules: {},
      anotherRules: {
        password: [
          { required: true, message: '请输入密码' },
          { validator: formValidate('validatePassword') },
        ],
        newpassword: [
          { required: true, message: '请输入密码' },
          {
            validator: (...args) => {
              if (args[1] !== this.submitForm.password) {
                args[2](new Error('两次密码不一致!'))
              } else {
                args[2]()
              }
            },
          },
        ],
        serviceMobile: [{ validator: formValidate('validateServiceMobile') }],
        area: [
          {
            required: true,
            message: '请选择地区',
          },
          {
            validator: (rules, value, callback) => {
              const hasCity = value.city && value.city !== ''
              const hasDistrict = value.district && value.district !== ''
              if (!hasCity || !hasDistrict) {
                callback(new Error('地址选择必须精确到区级'))
              } else {
                callback()
              }
            },
          },
        ],
        cooperationUrl: [{ required: true, message: '请上传合作协议' }],
      },
      mobileRules: {
        password: [
          { required: true, message: '请输入密码' },
          { validator: formValidate('validatePassword') },
        ],
        newpassword: [
          { required: true, message: '请输入密码' },
          {
            validator: (...args) => {
              if (args[1] !== this.submitForm.password) {
                args[2](new Error('两次密码不一致!'))
              } else {
                args[2]()
              }
            },
          },
        ],
        serviceMobile: [{ validator: formValidate('validateServiceMobile') }],
        area: [
          {
            required: true,
            message: '请选择地区',
          },
          {
            validator: (rules, value, callback) => {
              const hasCity = value.city && value.city !== ''
              const hasDistrict = value.district && value.district !== ''
              const merchantLevel = this.submitForm.merchantLevel
              if (merchantLevel === 'PROVINCE' && (hasCity || hasDistrict)) {
                callback(new Error('地址选择必须精确到省级'))
              } else if (
                merchantLevel === 'CITY' &&
                (!hasCity || hasDistrict)
              ) {
                callback(new Error('地址选择必须精确到市级'))
              } else if (merchantLevel === 'DISTRICT' && !hasDistrict) {
                callback(new Error('地址选择必须精确到区级'))
              } else {
                callback()
              }
            },
          },
        ],
        licenseUrl: [{ required: true, message: '请上传营业执照' }],
      },
      labelWidth: 200,
      agentApplyFormItems: [
        {
          type: 'text',
          value: 'userName',
          label: '商户名',
          required: true,
          clearable: true,
          placeholder: '仅限文字及字母，不超过30个字符',
        },
        {
          type: 'radio',
          value: 'merchantType',
          label: '商户属性',
          required: true,
          options: [
            {
              text: '其他运营方',
              label: 'ANOTHER',
            },
            {
              text: '移动或铁通官方账号',
              label: 'OFFICIAL',
            },
          ],
        },
        {
          type: 'text',
          value: 'name',
          clearable: true,
          label: '管理员姓名',
          placeholder: '仅限文字及字母，不超过20个字符',
          required: true,
        },
        {
          type: 'text',
          value: 'mobile',
          label: '手机号',
          clearable: true,
          placeholder: '请输入11位手机号码',
          required: true,
        },
        {
          slot: 'imgCode',
        },
        {
          slot: 'code',
        },
      ],
      agentApplyFormRules: {
        userName: [
          {
            max: 30,
            message: '最多允许输入30个字符',
            trigger: ['change', 'blur'],
          },
          {
            validator: formValidate('validateUserName'),
            trigger: ['change', 'blur'],
          },
        ],
        name: [
          {
            max: 20,
            message: '最多允许输入20个字符',
            trigger: ['change', 'blur'],
          },
          {
            validator: formValidate('validateUserName'),
            trigger: ['change', 'blur'],
          },
        ],
        mobile: [
          {
            validator: formValidate('validateMobile'),
            trigger: ['change', 'blur'],
          },
        ],
        imgCode: [
          {
            required: true,
            message: '请输入图形验证码',
          },
        ],
        code: [
          {
            required: true,
            message: '请输入验证码',
          },
          {
            validator: formValidate('vaildateInteger'),
            trigger: ['change', 'blur'],
          },
        ],
      },
      time: '',
      step: 1,
      loading: false,
    }
  },
  created() {
    this.createCode()
  },
  methods: {
    handleApply() {
      this.$refs.submitForm.validate((valid) => {
        if (!valid) return

        let params = {}

        if (this.agentApplyFormData.merchantType === 'ANOTHER') {
          params.merchantType = 'ANOTHER'
          delete this.submitForm.merchantType
        } else {
          params.merchantType = this.submitForm.merchantType
        }

        delete this.agentApplyFormData.merchantType

        if (this.submitForm.area && this.submitForm.area.province)
          this.submitForm.province = this.submitForm.area.province
        if (this.submitForm.area && this.submitForm.area.city)
          this.submitForm.city = this.submitForm.area.city
        if (this.submitForm.area && this.submitForm.area.district)
          this.submitForm.district = this.submitForm.area.district

        if (!this.merchantCode) throw Error('no merchantcode')
        params = {
          ...params,
          ...this.submitForm,
          ...this.agentApplyFormData,
          merchantCode: this.merchantCode,
          applyType: 'APPLY',
        }

        delete params.area
        getWebLoginImg({ rsa: true }).then((res) => {
          this.publicKey = res.headers && res.headers['rsa-public-key']
          this.checkKey = res.headers && res.headers['rsa-check-key']
          localStorage.setItem('checkKey', this.checkKey)
          let encryptor = new JSEncrypt()
          encryptor.setPublicKey(this.publicKey)

          // let p = encryptor.encrypt(md5(params.password))
          let p = md5(params.password)
          params.password = p
          params.newpassword = p

          merchantApply(params)
            .then(() => {
              this.$message({
                showclose: true,
                message: '申请成功,请耐心等待审核',
                type: 'success',
              })

              this.$router.push('/login')
            })
            .catch((err) => {
              console.log(err)
            })
            .finally(() => {})
        })
      })
    },
    createCode() {
      // this.time = new Date().getTime()
      // const authCodeApi =
      //   process.env.VUE_APP_BASE_URL_API +
      //   '/open/getSystemUserLoginCerificationImg'
      // this.authCodeSrc = `${authCodeApi}?uuid=${this.time}`
      getWebLoginImg({ rsa: true }).then((res) => {
        this.publicKey = res.headers && res.headers['rsa-public-key']
        this.checkKey = res.headers && res.headers['rsa-check-key']
        localStorage.setItem('checkKey', this.checkKey)
        let reader = new FileReader()
        reader.readAsDataURL(res.data)
        reader.onload = (evt) => {
          let imageString = evt.target.result
          this.authCodeSrc = imageString
        }
      })
    },
    nextStep(e) {
      e.preventDefault()
      this.$refs.agentApplyForm.validate((valid) => {
        if (valid) {
          this.loading = true
          let params = {
            mobile: this.agentApplyFormData.mobile,
            code: this.agentApplyFormData.code,
          }

          // if (this.agentApplyFormData.merchantType !== 'ANOTHER') {
          //   this.submitForm = {
          //     merchantType: 'CMCC'
          //   }
          // }

          // let tempArr = cloneDeep(this.submitFormItems)
          // let licenceIndex = tempArr.findIndex(item => item.slot === 'licenseUrl')
          // let cooperationIndex = tempArr.findIndex(item => item.slot === 'cooperationUrl')

          // if (licenceIndex < 0 || cooperationIndex < 0) return

          // tempArr.splice(licenceIndex, 1, this.submitFormItems[cooperationIndex])
          // tempArr.splice(cooperationIndex, 1, this.submitFormItems[licenceIndex])

          // if (this.agentApplyFormData.merchantType === 'ANOTHER') {
          //   this.submitFormRules = this.anotherRules
          // } else {
          //   this.submitFormRules = this.mobileRules
          //   this.submitFormItems = tempArr
          // }

          // this.step = 2

          // this.$nextTick(() => {
          //   this.$refs.submitForm.clearValidate()
          // })

          // return

          openMerchantCode(params)
            .then((res) => {
              this.loading = false

              if (this.agentApplyFormData.merchantType !== 'ANOTHER') {
                this.submitForm = {
                  merchantType: 'CMCC',
                }
              }

              let tempArr = cloneDeep(this.submitFormItems)
              let licenceIndex = tempArr.findIndex(
                (item) => item.slot === 'licenseUrl'
              )
              let cooperationIndex = tempArr.findIndex(
                (item) => item.slot === 'cooperationUrl'
              )

              if (licenceIndex < 0 || cooperationIndex < 0) return

              tempArr.splice(
                licenceIndex,
                1,
                this.submitFormItems[cooperationIndex]
              )
              tempArr.splice(
                cooperationIndex,
                1,
                this.submitFormItems[licenceIndex]
              )

              if (this.agentApplyFormData.merchantType === 'ANOTHER') {
                this.submitFormRules = this.anotherRules
              } else {
                this.submitFormRules = this.mobileRules
                this.submitFormItems = tempArr
              }

              this.step = 2

              this.$nextTick(() => {
                this.$refs.submitForm.clearValidate()
              })

              this.merchantCode = res.merchantCode
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          this.$message('请检查所有信息是否填写完成!')
        }
      })
    },
    apply() {},
  },
}
</script>

<style lang="scss" scoped>
.agent-apply-agreement {
  padding-left: 200px;
  padding-bottom: 20px;

  a {
    color: #005be5;
  }
}

.hidden-form {
  display: none;
}
.mobile-dialog-autcode_content {
  display: flex;

  .mobile-dialog-autcode_content_right {
    margin-left: 20px;
    display: flex;
    min-width: 188px;
    max-width: 188px;

    img {
      width: 100px;
      height: 40px;
    }
  }

  .create-code {
    margin-left: 14px;
    cursor: pointer;
  }
}
.agent-apply__wrapper {
  width: 100%;
  height: 100vh;
  min-height: 600px;
  min-width: 600px;
  background: url(../../assets/images/back-login.png) center no-repeat;
  background-size: 100% 100%;
  overflow: hidden;
  .logo-img {
    margin: 40px auto auto 55px;
    display: flex;
    align-items: center;
    img:nth-child(1) {
      width: 106px;
      margin-right: 30px;
    }
  }
  .agent-apply__body {
    width: 50%;
    height: 90%;
    border: 1px solid green;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    background: #fff;
    padding: 20px 60px;
    border-radius: 10px;
    overflow: auto;
    .title {
      font-size: 16px;
      font-weight: 400;
      color: #79797b;
      text-align: center;
      margin-bottom: 30px;
      &::before {
        content: '';
        display: block;
        width: 62px;
        height: 4px;
        background: #4c71f9;
        border-radius: 2px;
        margin: auto auto 10px;
      }
    }
  }
}
</style>
<style lang="scss">
.agent-apply-buttons {
  display: flex;
  justify-content: center;

  .el-button {
    width: 200px;
  }
}
.mobile-dialog-autcode_button {
  .el-button {
    margin-left: 40px;
    margin-right: 28px;
    height: 40px;
  }
}
</style>
